﻿using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace JX.Infrastructure.Middleware
{
    /// <summary>
    /// 图片防盗链中间件
    /// </summary>
    public class HotlinkingPreventionMiddleware
    {
        private readonly string _wwwrootFolder;
        private readonly RequestDelegate _next;
        /// <summary>
        /// 构造器注入
        /// </summary>
        /// <param name="next"></param>
        /// <param name="env"></param>
        public HotlinkingPreventionMiddleware(RequestDelegate next, IHostingEnvironment env)
        {
            _wwwrootFolder = env.WebRootPath;
            _next = next;
        }

        /// <summary>
        /// 通过urlReferrer来防止图片盗链
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            var applicationUrl = $"{context.Request.Scheme}://{context.Request.Host.Value}";
            var headersDictionary = context.Request.Headers;
            var urlReferrer = headersDictionary[HeaderNames.Referer].ToString();

            if (!string.IsNullOrEmpty(urlReferrer) && !urlReferrer.StartsWith(applicationUrl))
            {
                var unauthorizedImagePath = Path.Combine(_wwwrootFolder, "Images/nopic.gif");

                await context.Response.SendFileAsync(unauthorizedImagePath);
            }

            await _next(context);
        }
    }
}
